package com.gao.shiro.demo.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Spring Security : 授权和验证
 * @author gaofeng
 * @date 2022年06月29日 19:45
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    /**
     * 配置如何通过拦截器保护请求
     * 授权
     * @param http
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests().antMatchers("/").permitAll()
//                                .antMatchers("/login").permitAll()
//                                .antMatchers("/hr/**").hasRole("VIP1")
//                                .antMatchers("/business/**").hasRole("SVIP") ;
        //开启认证：URL格式登录必须是httpBasic
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic();

        // 没有权限,就到登录页面
        http.formLogin() ;

        // 开启注销
//        http.logout().logoutUrl("/login") ;

        // 防止跨站攻击, csrf明文传输不安全,默认开启
        http.csrf().disable() ;
        http.logout().logoutSuccessUrl("/") ;
    }

    /**
     * 可配置user-detail（用户详细信息）服务
     * 认证
     * Spring Security 5.0+ 增加了很多加密方法,明文密码会报错
     * @param auth
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("gaofeng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip", "svip")
                .and()
                .withUser("fangqing").password("123456").roles("vip1") ;
        // 读数据库
//        auth.jdbcAuthentication().dataSource(new DruidDataSource()).withDefaultSchema().withUser("fangqing").password("123456").roles("vip1") ;
    }

    /**
     * 重载该方法,可配置Spring Security 的Filter链
     * Spring Security 5.0+ 增加了很多加密方法,明文密码会报错
     * @param web
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        super.configure(web);
    }
}
